<template>
    <div class="idcard-container">
        <div class="control-panel">
            <div class="options-panel">
                <div class="area-select">
                    <span>地区:</span>
                    <div class="area-input">
                        <n-cascader v-model:value="selectedArea" :options="areaOptions" placeholder="选择地区（可选）"
                            class="area-field" clearable @update:value="handleAreaChange" />
                    </div>
                </div>
                <div class="gender-select">
                    <span>性别:</span>
                    <n-radio-group v-model:value="gender">
                        <n-radio-button value="any">随机</n-radio-button>
                        <n-radio-button value="male">男</n-radio-button>
                        <n-radio-button value="female">女</n-radio-button>
                    </n-radio-group>
                </div>
                <div class="action-panel">
                    <n-space>
                        <n-input-number v-model:value="count" :min="1" :max="100" placeholder="生成数量"
                            class="count-input" />
                        <n-button type="primary" @click="generateId">生成</n-button>
                        <n-button @click="copyAll" :disabled="idCards.length === 0">
                            复制全部
                        </n-button>
                        <n-button @click="clearAll" :disabled="idCards.length === 0">
                            清空
                        </n-button>
                    </n-space>
                </div>
            </div>
        </div>

        <div class="result-panel">
            <div v-if="idCards.length === 0" class="empty-tip">
                点击生成按钮开始生成身份证号
            </div>
            <n-scrollbar v-else>
                <div v-for="(id, index) in currentPageData" :key="index" class="id-item">
                    <div class="id-info">
                        <span class="id-number">{{ id.number }}</span>
                        <span class="id-detail">
                            {{ id.area }} | {{ id.birth }} | {{ id.gender }}
                        </span>
                    </div>
                    <n-button quaternary circle size="small" @click="copyId(id.number)">
                        复制
                    </n-button>
                </div>
                <div class="pagination-container">
                    <n-pagination v-model:page="currentPage" :page-size="pageSize" :item-count="idCards.length"
                        :show-size-picker="false" :show-quick-jumper="true" />
                </div>
            </n-scrollbar>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import view from '@renderer/util/ui/ViewUtil'
import areaData from './area'

// 选项
const selectedArea = ref<string>('')
const gender = ref<'any' | 'male' | 'female'>('any')
const count = ref(5)

// 生成结果
const idCards = ref<Array<{
    number: string
    area: string
    birth: string
    gender: string
}>>([])

// 地区选项
const areaOptions = areaData

// 分页相关
const currentPage = ref(1)
const pageSize = 5

// 计算当前页数据
const currentPageData = computed(() => {
    const start = (currentPage.value - 1) * pageSize
    const end = start + pageSize
    return idCards.value.slice(start, end)
})

// 处理地区选择变化
const handleAreaChange = (value: string | null) => {
    console.log('value', value, typeof value)
    selectedArea.value = value || ''
}

// 生成身份证号
const generateId = () => {
    currentPage.value = 1  // 重置到第一页
    const results: typeof idCards.value = []

    for (let i = 0; i < count.value; i++) {
        // 生成地区码
        let areaCode = ''
        if (selectedArea.value) {
            const selectedCode = selectedArea.value
            console.log('selectedCode', selectedCode)
            // 根据选中的地区码长度决定处理方式
            if (selectedCode.length === 6) {
                // 区县级，直接使用
                areaCode = selectedCode
            } else {
                // 查找选中区域
                const findArea = (areas: any[], targetValue: string): any => {
                    for (const area of areas) {
                        if (area.value === targetValue) {
                            return area
                        }
                        if (area.children) {
                            const found = findArea(area.children, targetValue)
                            if (found) return found
                        }
                    }
                    return null
                }

                const selectedArea = findArea(areaOptions, selectedCode)
                if (!selectedArea) {
                    view.alertErrorMessage('地区数据错误')
                    return
                }

                if (selectedCode.length === 4) {
                    // 市级，随机选择下级区县
                    const districts = selectedArea.children || []
                    if (districts.length === 0) {
                        view.alertErrorMessage('地区数据错误')
                        return
                    }
                    areaCode = districts[Math.floor(Math.random() * districts.length)].value
                } else if (selectedCode.length === 2) {
                    // 省级，随机选择下两级直到区县
                    const cities = selectedArea.children || []
                    if (cities.length === 0) {
                        view.alertErrorMessage('地区数据错误')
                        return
                    }
                    const randomCity = cities[Math.floor(Math.random() * cities.length)]
                    const districts = randomCity.children || []
                    if (districts.length === 0) {
                        view.alertErrorMessage('地区数据错误')
                        return
                    }
                    areaCode = districts[Math.floor(Math.random() * districts.length)].value
                }
            }
        } else {
            // 完全随机选择
            const provinces = areaOptions
            const province = provinces[Math.floor(Math.random() * provinces.length)]
            const cities = province.children || []
            const city = cities[Math.floor(Math.random() * cities.length)]
            const areas = city.children || []
            const area = areas[Math.floor(Math.random() * areas.length)]
            areaCode = area.value
        }
        // 验证地区码格式
        if (!areaCode || areaCode.length !== 6) {
            view.alertErrorMessage('地区码格式错误')
            return
        }

        // 生成出生日期
        const start = new Date('1950-01-01').getTime()
        const end = new Date().getTime()
        const timestamp = start + Math.random() * (end - start)
        const date = new Date(timestamp)
        const birthString = date.toISOString().slice(0, 10).replace(/-/g, '')

        // 生成顺序码（包含性别信息）
        let sequenceCode = ''
        for (let j = 0; j < 3; j++) {
            sequenceCode += Math.floor(Math.random() * 10)
        }
        // 根据性别调整顺序码
        const lastDigit = parseInt(sequenceCode[2])
        if (gender.value === 'male' && lastDigit % 2 === 0) {
            sequenceCode = sequenceCode.slice(0, -1) + (lastDigit + 1)
        } else if (gender.value === 'female' && lastDigit % 2 === 1) {
            sequenceCode = sequenceCode.slice(0, -1) + (lastDigit - 1)
        }

        // 拼接前17位
        const id17 = areaCode + birthString + sequenceCode

        // 计算校验码
        const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

        let sum = 0
        for (let j = 0; j < 17; j++) {
            sum += parseInt(id17[j]) * weights[j]
        }

        const checkCode = checkCodes[sum % 11]
        const idNumber = id17 + checkCode

        // 获取地区名称
        const getAreaName = (code: string): string => {
            // 查找完整路径
            const findPath = (areas: any[], targetCode: string, path: string[] = []): string[] | null => {
                for (const area of areas) {
                    if (area.value === targetCode) {
                        return [...path, area.label]
                    }
                    if (area.children) {
                        const result = findPath(area.children, targetCode, [...path, area.label])
                        if (result) {
                            return result
                        }
                    }
                }
                return null
            }

            const path = findPath(areaOptions, code)
            return path ? path.join(' ') : code
        }

        // 添加到结果
        results.push({
            number: idNumber,
            area: getAreaName(areaCode),
            birth: `${birthString.slice(0, 4)}-${birthString.slice(4, 6)}-${birthString.slice(6, 8)}`,
            gender: parseInt(sequenceCode[2]) % 2 === 0 ? '女' : '男'
        })
    }

    idCards.value = results
}

// 复制单个身份证号
const copyId = async (id: string) => {
    try {
        await navigator.clipboard.writeText(id)
        view.alertSuccessMessage('复制成功')
    } catch (error) {
        view.alertErrorMessage('复制失败')
    }
}

// 复制全部
const copyAll = async () => {
    try {
        const text = idCards.value.map(id => id.number).join('\n')
        await navigator.clipboard.writeText(text)
        view.alertSuccessMessage('全部复制成功')
    } catch (error) {
        view.alertErrorMessage('复制失败')
    }
}

// 清空
const clearAll = () => {
    idCards.value = []
    currentPage.value = 1
}
</script>

<style scoped>
.idcard-container {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.control-panel {
    display: flex;
    gap: 16px;
    padding: 16px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    align-items: flex-start;
}

.options-panel {
    flex: 1;
    display: flex;
    gap: 16px;
    align-items: center;
    flex-wrap: wrap;
}

.area-select,
.gender-select,
.action-panel {
    display: flex;
    align-items: center;
    gap: 8px;
}

.area-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.area-field {
    width: 240px;
}

.result-panel {
    flex: 1;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.empty-tip {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-color-3);
}

.id-item {
    padding: 8px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--border-color);
    transition: background-color 0.2s;
}

.id-item:hover {
    background-color: var(--hover-color);
}

.id-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.id-number {
    font-family: monospace;
    font-size: 16px;
    user-select: all;
}

.id-detail {
    font-size: 12px;
    color: var(--text-color-3);
}

.count-input {
    width: 120px;
}

.pagination-container {
    padding: 16px;
    display: flex;
    justify-content: center;
    border-top: 1px solid var(--border-color);
}
</style>